<template>
  <div class="product-storage-page">
    <el-card shadow="never" class="breadcrumb-card">
      <div class="breadcrumb-content">
        <div class="breadcrumb-title">
          <el-icon class="breadcrumb-icon">
            <Box />
          </el-icon>
          <div>
            <p class="breadcrumb-subtitle">仓库管理 · 产品入库</p>
            <h2 class="breadcrumb-heading">产品入库</h2>
          </div>
        </div>
        <el-breadcrumb :separator-icon="ArrowRight">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>仓库管理</el-breadcrumb-item>
          <el-breadcrumb-item>产品入库</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </el-card>

    <el-card shadow="never" class="search-card">
      <div class="search-card__header">
        <h3>高级筛选</h3>
        <span>支持编号、产品、日期与状态组合查询</span>
      </div>
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="入库单编号/名称">
          <el-input
            v-model="searchForm.inboundCodeName"
            placeholder="请输入入库单编号/名称"
            clearable
            class="search-input"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="产品名称/编号">
          <el-input
            v-model="searchForm.productKeyword"
            placeholder="请输入产品名称/编号"
            clearable
            class="search-input"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Cpu /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="入库日期">
          <el-date-picker
            v-model="searchForm.inboundDate"
            type="date"
            placeholder="请选择入库日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            clearable
            class="search-input"
            :prefix-icon="Calendar"
          />
        </el-form-item>
        <el-form-item label="入库状态">
          <el-select
            v-model="searchForm.stats"
            placeholder="全部"
            clearable
            class="search-input"
          >
            <el-option label="待入库" :value="0" />
            <el-option label="已确认" :value="1" />
            <el-option label="已入库" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item class="search-actions">
          <el-button :icon="RefreshLeft" @click="handleReset">重置</el-button>
          <el-button
            type="primary"
            :loading="loading"
            :icon="Search"
            @click="handleSearch"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="never" class="table-card">
      <div class="table-header">
        <div class="table-header__info">
          <h3 class="table-title">
            <el-icon class="table-title-icon"><Box /></el-icon>
            产品入库列表
          </h3>
          <p class="table-subtitle">
            共 <strong>{{ pagination.totalCount }}</strong> 条数据，当前第
            <strong>{{ pagination.pageIndex }}</strong
            >/<strong>{{ totalPages }}</strong> 页
          </p>
          <el-tag
            v-if="multipleSelection.length > 0"
            type="info"
            class="selection-tag"
          >
            已选择 {{ multipleSelection.length }} 项
          </el-tag>
        </div>
        <div class="table-header__actions">
          <el-button
            type="primary"
            :icon="Plus"
            @click="handleAdd"
            class="action-btn add-btn"
            >新增产品入库</el-button
          >
          <el-button
            type="success"
            :icon="Download"
            :loading="exportLoading"
            @click="handleExport"
            class="action-btn export-btn"
            >导出</el-button
          >
          <el-button
            type="danger"
            :disabled="!multipleSelection.length"
            @click="handleBatchDelete"
            class="action-btn batch-delete-btn"
            >批量删除</el-button
          >
        </div>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        class="modern-table"
        border
        highlight-current-row
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          type="index"
          label="序号"
          width="60"
          :index="getIndex"
        />
        <el-table-column
          prop="inboundOrderName"
          label="入库单名称"
          min-width="160"
        >
          <template #default="{ row }">
            <span class="table-strong">{{ row.inboundOrderName || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="inboundOrderNo"
          label="入库单编号"
          min-width="150"
        >
          <template #default="{ row }">
            <span class="table-code">{{ row.inboundOrderNo || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="inboundDate" label="入库日期" min-width="130">
          <template #default="{ row }">
            <span class="table-date">{{ formatDate(row.inboundDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="workOrderName"
          label="生产工单"
          min-width="150"
        />
        <el-table-column prop="workOrderNo" label="工单编号" min-width="150" />
        <el-table-column prop="productName" label="产品名称" min-width="150" />
        <el-table-column prop="productNo" label="产品编号" min-width="150" />
        <el-table-column
          prop="specification"
          label="规格型号"
          min-width="130"
        />
        <el-table-column prop="unit" label="单位" min-width="80" />
        <el-table-column
          prop="inboundQuantity"
          label="入库数量"
          min-width="110"
          align="right"
        />
        <el-table-column
          prop="warehouseDisplayName"
          label="仓库名称"
          min-width="140"
        >
          <template #default="{ row }">
            {{ row.warehouseDisplayName || "-" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="reservoirDisplayName"
          label="库区名称"
          min-width="140"
        >
          <template #default="{ row }">
            {{ row.reservoirDisplayName || "-" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="seatDisplayName"
          label="库位名称"
          min-width="140"
        >
          <template #default="{ row }">
            {{ row.seatDisplayName || "-" }}
          </template>
        </el-table-column>
        <el-table-column label="入库状态" min-width="120" align="center">
          <template #default="{ row }">
            <el-tag
              :type="getStatusMeta(row.stats).tagType"
              effect="light"
              class="status-tag"
              round
            >
              {{ getStatusMeta(row.stats).label }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="320" fixed="right" align="center">
          <template #default="{ row }">
            <div class="table-actions">
              <el-button
                v-if="row.stats === 0"
                type="primary"
                link
                size="small"
                class="table-action-btn confirm-btn"
                @click="handleConfirmInfo(row)"
                >确认入库信息</el-button
              >
              <el-button
                v-if="row.stats === 1"
                type="success"
                link
                size="small"
                class="table-action-btn inbound-btn"
                :loading="isActionLoading(row.id, 'inbound')"
                :disabled="isActionLoading(row.id, 'inbound')"
                @click="handleInbound(row)"
                >入库</el-button
              >
              <el-button
                v-if="row.stats === 2"
                type="warning"
                link
                size="small"
                class="table-action-btn revoke-btn"
                :loading="isActionLoading(row.id, 'revoke')"
                :disabled="isActionLoading(row.id, 'revoke')"
                @click="handleRevoke(row)"
                >撤回</el-button
              >
              <el-button
                type="primary"
                link
                size="small"
                @click="handleEdit(row)"
                class="table-action-btn edit-btn"
                >编辑</el-button
              >
              <el-button
                type="danger"
                link
                size="small"
                @click="handleDelete(row)"
                class="table-action-btn delete-btn"
                >删除</el-button
              >
            </div>
          </template>
        </el-table-column>
        <template #empty>
          <div class="empty-state">
            <div class="empty-icon-wrapper">
              <el-icon class="empty-icon"><Box /></el-icon>
            </div>
            <p class="empty-text">暂无产品入库数据</p>
            <p class="empty-hint">点击“新增产品入库”创建第一条数据</p>
            <el-button
              type="primary"
              :icon="Plus"
              @click="handleAdd"
              class="empty-action-btn"
              >立即创建入库单</el-button
            >
          </div>
        </template>
      </el-table>
      <div class="table-pagination">
        <div class="pagination-wrapper">
          <div class="pagination-info">
            <div class="pagination-info-item">
              <el-icon class="info-icon"><Box /></el-icon>
              <span class="pagination-text"
                >共
                <strong class="highlight-number">{{
                  pagination.totalCount
                }}</strong>
                条记录</span
              >
            </div>
            <div class="pagination-info-item">
              <span class="pagination-text"
                >每页显示
                <strong class="highlight-number">{{
                  pagination.pageSize
                }}</strong>
                条</span
              >
            </div>
            <div class="pagination-info-item">
              <span class="pagination-text"
                >第
                <strong class="highlight-number">{{
                  pagination.pageIndex
                }}</strong>
                /
                <strong class="highlight-number">{{ totalPages }}</strong>
                页</span
              >
            </div>
          </div>
          <div class="pagination-controls">
            <div class="pagination-buttons">
              <el-button
                size="default"
                @click="gotoFirst"
                :disabled="pagination.pageIndex === 1"
                class="pagination-btn pagination-btn-first"
                :icon="DArrowLeft"
                >首页</el-button
              >
              <el-button
                size="default"
                @click="gotoPrev"
                :disabled="pagination.pageIndex === 1"
                class="pagination-btn pagination-btn-prev"
                :icon="ArrowLeft"
                >上一页</el-button
              >
            </div>
            <el-pagination
              v-model:current-page="pagination.pageIndex"
              v-model:page-size="pagination.pageSize"
              :page-sizes="[10, 20, 30, 50]"
              background
              layout="prev, pager, next, sizes"
              :total="pagination.totalCount"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              class="pagination-component"
            />
            <div class="pagination-buttons">
              <el-button
                size="default"
                @click="gotoNext"
                :disabled="pagination.pageIndex >= totalPages"
                class="pagination-btn pagination-btn-next"
                >下一页<el-icon class="btn-icon-right"
                  ><ArrowRightIcon /></el-icon
              ></el-button>
              <el-button
                size="default"
                @click="gotoLast"
                :disabled="pagination.pageIndex >= totalPages"
                class="pagination-btn pagination-btn-last"
                >尾页<el-icon class="btn-icon-right"><DArrowRight /></el-icon
              ></el-button>
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import {
  ArrowRight,
  Box,
  Search,
  Calendar,
  Plus,
  RefreshLeft,
  Cpu,
  DArrowLeft,
  DArrowRight,
  ArrowLeft,
  ArrowRight as ArrowRightIcon,
  Download,
} from "@element-plus/icons-vue";
import { onMounted, reactive, ref, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import https from "@/Http/http";
import moment from "moment";

const router = useRouter();

type StatusTagType = "" | "success" | "warning" | "info" | "danger";

interface StatusMeta {
  label: string;
  tagType: StatusTagType;
}

const STATUS_META: Record<number, StatusMeta> = {
  0: { label: "待入库", tagType: "danger" },
  1: { label: "确认入库", tagType: "warning" },
  2: { label: "已入库", tagType: "success" },
};

const getStatusMeta = (status?: number | null): StatusMeta => {
  const normalized = Number.isFinite(status) ? Number(status) : 0;
  return STATUS_META[normalized] ?? { label: "未知", tagType: "info" };
};

interface ProductStorageItem {
  id: number;
  inboundOrderNo: string;
  inboundOrderName: string;
  inboundDate?: string;
  workOrderName: string;
  workOrderNo?: string;
  remark?: string;
  stats: number;
  productName: string;
  productNo: string;
  specification?: string;
  productTypeId?: number;
  unit?: string;
  batchNo?: string;
  inboundQuantity?: number;
  productionDate?: string;
  expiryDate?: string;
  warehouseName?: string;
  warehousePrincipal?: string;
  warehouseDisplayName?: string;
  reservoirDisplayName?: string;
  seatDisplayName?: string;
}

const tableData = ref<ProductStorageItem[]>([]);
const loading = ref(false);
const multipleSelection = ref<ProductStorageItem[]>([]);
const exportLoading = ref(false);
const statusActionLoading = ref<{
  id: number | null;
  action: "inbound" | "revoke" | null;
}>({
  id: null,
  action: null,
});

const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0,
  pageCount: 0,
});

const searchForm = reactive({
  inboundCodeName: "",
  productKeyword: "",
  inboundDate: "" as string | null,
  stats: null as number | null,
});

const totalPages = computed(() =>
  Math.max(1, Math.ceil(pagination.totalCount / pagination.pageSize))
);

const getIndex = (index: number) => {
  return (pagination.pageIndex - 1) * pagination.pageSize + index + 1;
};

const formatDate = (date: string | Date | null | undefined) => {
  if (!date) return "-";
  return moment(date).format("YYYY-MM-DD");
};

const splitWarehouseLocation = (rawName?: string | null) => {
  const parts = (rawName ?? "")
    .split(/\s+/)
    .map((item) => item.trim())
    .filter(Boolean);
  return {
    warehouse: parts[0] ?? "",
    reservoir: parts[1] ?? "",
    seat: parts[2] ?? "",
  };
};

const buildQueryParams = () => {
  const params: Record<string, unknown> = {
    PageIndex: pagination.pageIndex,
    PageSize: pagination.pageSize,
  };

  if (searchForm.inboundCodeName) {
    params.InboundCodeName = searchForm.inboundCodeName.trim();
  }
  if (searchForm.productKeyword) {
    params.ProductKeyword = searchForm.productKeyword.trim();
  }
  if (searchForm.inboundDate) {
    params.InboundDate = searchForm.inboundDate;
  }
  if (searchForm.stats !== null && searchForm.stats !== undefined) {
    params.Stats = searchForm.stats;
  }
  return params;
};

const parseResponse = (res: any) => {
  const responseData = res?.data ?? {};
  const code = responseData.code ?? responseData.Code;
  let dataList: any[] = [];
  let total = 0;
  let pageCount = 0;

  if (responseData.data !== undefined) {
    dataList = Array.isArray(responseData.data) ? responseData.data : [];
    total = responseData.totalCount ?? 0;
    pageCount = responseData.pageCount ?? 0;
  } else if (responseData.Data !== undefined) {
    dataList = Array.isArray(responseData.Data) ? responseData.Data : [];
    total = responseData.TotalCount ?? 0;
    pageCount = responseData.PageCount ?? 0;
  }

  if (code === -1) {
    const msg = responseData.msg ?? responseData.Msg ?? "获取产品入库列表失败";
    throw new Error(msg);
  }

  return {
    list: dataList,
    total,
    pageCount,
  };
};

const loadProductStorageList = () => {
  loading.value = true;
  https.Reads.get("/Warehouse/ProductStorageList", {
    params: buildQueryParams(),
  })
    .then((res: any) => {
      const { list, total, pageCount } = parseResponse(res);
      tableData.value = list.map((item: ProductStorageItem) => {
        const rawWarehouseName =
          (item as any).warehouseName ??
          (item as any).warehouseDisplayName ??
          item.warehouseName ??
          "";
        const { warehouse, reservoir, seat } =
          splitWarehouseLocation(rawWarehouseName);
        const normalizedWarehouse =
          (item as any).warehouseDisplayName ?? warehouse;
        const normalizedReservoir =
          (item as any).reservoirDisplayName ?? reservoir;
        const normalizedSeat = (item as any).seatDisplayName ?? seat;

        return {
          ...item,
          stats: Number(
            (item as any).stats ??
              (item as any).Stats ??
              (item as any).status ??
              0
          ),
          warehouseName: rawWarehouseName,
          warehouseDisplayName: normalizedWarehouse,
          reservoirDisplayName: normalizedReservoir,
          seatDisplayName: normalizedSeat,
        };
      });
      pagination.totalCount = total;
      pagination.pageCount = pageCount;
    })
    .catch((error: any) => {
      console.error("获取产品入库列表失败:", error);
      const msg =
        error?.message ??
        error?.response?.data?.msg ??
        "获取产品入库列表失败，请稍后重试";
      ElMessage.error(msg);
      tableData.value = [];
      pagination.totalCount = 0;
    })
    .finally(() => {
      loading.value = false;
    });
};

onMounted(() => {
  loadProductStorageList();
});

const handleSearch = () => {
  pagination.pageIndex = 1;
  loadProductStorageList();
};

const isActionLoading = (rowId: number, action: "inbound" | "revoke") => {
  return (
    statusActionLoading.value.id === rowId &&
    statusActionLoading.value.action === action
  );
};

const setStatusActionLoading = (
  id: number | null,
  action: "inbound" | "revoke" | null
) => {
  statusActionLoading.value = { id, action };
};

const handleInbound = (row: ProductStorageItem) => {
  if (row.stats !== 1) {
    ElMessage.warning("仅确认入库状态可执行入库");
    return;
  }
  ElMessageBox.confirm("确认要入库吗？", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      setStatusActionLoading(row.id, "inbound");
      return https.Writes.put("/Warehouse/AffirmProduct", {
        Id: row.id,
        Stats: row.stats,
      });
    })
    .then((res: any) => {
      if ((res?.data?.code ?? res?.data?.Code) === 1) {
        ElMessage.success(res?.data?.msg ?? "入库成功");
        loadProductStorageList();
      } else {
        throw new Error(res?.data?.msg ?? "入库失败");
      }
    })
    .catch((error: any) => {
      if (error !== "cancel") {
        console.error("入库失败:", error);
        ElMessage.error(error?.message ?? "入库失败，请稍后重试");
      } else {
        ElMessage.info("已取消入库");
      }
    })
    .finally(() => {
      setStatusActionLoading(null, null);
    });
};

const handleConfirmInfo = (row: ProductStorageItem) => {
  if (row.stats !== 0) {
    ElMessage.warning("仅待入库状态可确认入库信息");
    return;
  }
  const payload = buildPayloadFromRow(row);
  router.push({
    path: "/ProductStorageConfirm",
    query: {
      confirmId: row.id.toString(),
      confirmData: encodeURIComponent(JSON.stringify(payload)),
    },
  });
};

const handleRevoke = (row: ProductStorageItem) => {
  if (row.stats !== 2) {
    ElMessage.warning("仅已入库状态可撤回");
    return;
  }
  ElMessageBox.confirm("确认将该入库单撤回到待入库状态吗？", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      setStatusActionLoading(row.id, "revoke");
      return https.Writes.put("/Warehouse/RevokeProduct", {
        Id: row.id,
      });
    })
    .then((res: any) => {
      if ((res?.data?.code ?? res?.data?.Code) === 1) {
        ElMessage.success(res?.data?.msg ?? "撤回成功");
        loadProductStorageList();
      } else {
        throw new Error(res?.data?.msg ?? "撤回失败");
      }
    })
    .catch((error: any) => {
      if (error !== "cancel") {
        console.error("撤回失败:", error);
        ElMessage.error(error?.message ?? "撤回失败，请稍后重试");
      } else {
        ElMessage.info("已取消撤回");
      }
    })
    .finally(() => {
      setStatusActionLoading(null, null);
    });
};

const handleReset = () => {
  searchForm.inboundCodeName = "";
  searchForm.productKeyword = "";
  searchForm.inboundDate = null;
  searchForm.stats = null;
  handleSearch();
};

const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  pagination.pageIndex = 1;
  loadProductStorageList();
};

const handleCurrentChange = (val: number) => {
  pagination.pageIndex = val;
  loadProductStorageList();
};

const gotoFirst = () => {
  if (pagination.pageIndex !== 1) {
    pagination.pageIndex = 1;
    loadProductStorageList();
  }
};

const gotoPrev = () => {
  if (pagination.pageIndex > 1) {
    pagination.pageIndex -= 1;
    loadProductStorageList();
  }
};

const gotoNext = () => {
  if (pagination.pageIndex < totalPages.value) {
    pagination.pageIndex += 1;
    loadProductStorageList();
  }
};

const gotoLast = () => {
  if (pagination.pageIndex !== totalPages.value) {
    pagination.pageIndex = totalPages.value;
    loadProductStorageList();
  }
};

const handleAdd = () => {
  router.push("/ProductStorageAdd");
};

const buildDetailFromRow = (row: ProductStorageItem) => ({
  id: null,
  productName: row.productName || "",
  productNo: row.productNo || "",
  specification: row.specification || "",
  productTypeId: row.productTypeId ?? 0,
  unit: row.unit || "",
  batchNo: row.batchNo || "",
  inboundQuantity: row.inboundQuantity ?? 0,
  productionDate: row.productionDate || null,
  expiryDate: row.expiryDate || null,
  warehouseName: row.warehouseName || "",
  warehousePrincipal: row.warehousePrincipal || "",
});

const buildPayloadFromRow = (row: ProductStorageItem) => ({
  id: row.id,
  inboundOrderNo: row.inboundOrderNo,
  inboundOrderName: row.inboundOrderName,
  inboundDate: row.inboundDate,
  workOrderName: row.workOrderName,
  workOrderNo: row.workOrderNo,
  stats: row.stats,
  remark: row.remark || "",
  detail: [buildDetailFromRow(row)],
});

const handleEdit = (row: ProductStorageItem) => {
  const payload = buildPayloadFromRow(row);
  router.push({
    path: "/ProductStorageAdd",
    query: {
      editId: row.id.toString(),
      editData: encodeURIComponent(JSON.stringify(payload)),
    },
  });
};

const handleDelete = (row: ProductStorageItem) => {
  ElMessageBox.confirm("确认要删除该产品入库单吗？", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      https.Writes.put("/Warehouse/ProductStorageDelete", { id: row.id })
        .then((res: any) => {
          if ((res.data?.code ?? res.data?.Code) === 1) {
            ElMessage.success(res.data?.msg ?? "删除成功");
            loadProductStorageList();
          } else {
            ElMessage.error(res.data?.msg ?? "删除失败");
          }
        })
        .catch((error: any) => {
          console.error("删除产品入库失败:", error);
          ElMessage.error("删除失败，请稍后重试");
        });
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

const handleSelectionChange = (val: ProductStorageItem[]) => {
  multipleSelection.value = val;
};

const handleBatchDelete = () => {
  if (!multipleSelection.value.length) {
    ElMessage.warning("请选择需要删除的产品入库单！");
    return;
  }
  const ids = multipleSelection.value.map((item) => item.id);
  ElMessageBox.confirm(
    `确认要批量删除选中的 ${ids.length} 条产品入库单吗？`,
    "提示",
    {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      https.Writes.delete("/Warehouse/ProductStorageDeletes", {
        data: { Ids: ids },
      })
        .then((res: any) => {
          if ((res.data?.code ?? res.data?.Code) === 1) {
            ElMessage.success(res.data?.msg ?? "批量删除成功");
            loadProductStorageList();
          } else {
            ElMessage.error(res.data?.msg ?? "批量删除失败");
          }
        })
        .catch((error: any) => {
          console.error("批量删除产品入库失败:", error);
          ElMessage.error("批量删除失败，请稍后重试");
        });
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

const handleExport = async () => {
  if (exportLoading.value) {
    return;
  }
  exportLoading.value = true;
  try {
    const params: Record<string, unknown> = {};
    if (searchForm.inboundCodeName) {
      params.InboundCodeName = searchForm.inboundCodeName.trim();
    }
    if (searchForm.productKeyword) {
      params.ProductKeyword = searchForm.productKeyword.trim();
    }
    if (searchForm.inboundDate) {
      params.InboundDate = searchForm.inboundDate;
    }
    if (searchForm.stats !== null && searchForm.stats !== undefined) {
      params.Stats = searchForm.stats;
    }
    const response = await https.Reads.get("/Warehouse/ProductStorageExport", {
      params,
      responseType: "blob",
    });
    const blob = new Blob([response.data], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    });
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    const timestamp = new Date()
      .toISOString()
      .replace(/[-:T]/g, "")
      .slice(0, 14);
    link.download = `产品入库明细_${timestamp}.xlsx`;
    link.click();
    URL.revokeObjectURL(url);
    ElMessage.success("导出任务已开始，请留意下载文件");
  } catch (error: any) {
    console.error("导出产品入库失败:", error);
    ElMessage.error("导出产品入库失败，请稍后重试");
  } finally {
    exportLoading.value = false;
  }
};
</script>

<style scoped>
.product-storage-page {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding-bottom: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.breadcrumb-card {
  border-radius: 14px;
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  border: none;
  color: #fff;
  box-shadow: 0 4px 12px rgba(79, 172, 254, 0.25);
}

.breadcrumb-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.breadcrumb-title {
  display: flex;
  align-items: center;
  gap: 16px;
}

.breadcrumb-icon {
  font-size: 32px;
  color: #fff;
}

.breadcrumb-heading {
  margin: 0;
  font-size: 22px;
  font-weight: 700;
}

.search-card {
  border-radius: 14px;
  border: none;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  background: #fff;
}

.search-card__header {
  display: flex;
  justify-content: space-between;
  align-items: baseline;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 2px solid #f0f2f5;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: flex-end;
}

.search-input {
  width: 240px;
}

.search-actions {
  margin-left: auto;
  display: flex;
  gap: 10px;
}

.table-card {
  border-radius: 14px;
  border: none;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  background: #fff;
}

.table-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  flex-wrap: wrap;
  gap: 16px;
  padding-bottom: 16px;
  border-bottom: 2px solid #f0f2f5;
}

.table-title {
  margin: 0 0 8px 0;
  font-size: 20px;
  font-weight: 700;
  display: flex;
  align-items: center;
  gap: 10px;
}

.table-title-icon {
  font-size: 22px;
  color: #4facfe;
}

.table-subtitle {
  margin: 4px 0 8px 0;
  color: #909399;
  font-size: 14px;
}

.action-btn {
  padding: 10px 20px;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.add-btn {
  background: linear-gradient(135deg, #00c6ff 0%, #0072ff 100%);
  border: none;
  color: #fff;
}

.batch-delete-btn {
  background: linear-gradient(135deg, #ff416c 0%, #ff4b2b 100%);
  border: none;
  color: #fff;
}

.export-btn {
  background: linear-gradient(135deg, #34d399 0%, #059669 100%);
  border: none;
  color: #fff;
}

.modern-table {
  border-radius: 8px;
  overflow: hidden;
}

.modern-table :deep(.el-table__header th) {
  background: rgba(79, 172, 254, 0.06);
  font-weight: 600;
}

.table-code {
  font-weight: 500;
  font-family: "Courier New", monospace;
  color: #606266;
  background: rgba(79, 172, 254, 0.08);
  padding: 4px 10px;
  border-radius: 4px;
  display: inline-block;
}

.table-date {
  color: #606266;
  font-size: 13px;
}

.table-strong {
  font-weight: 600;
  color: #303133;
}

.status-tag {
  min-width: 86px;
  justify-content: center;
  font-weight: 500;
}

.table-actions {
  display: flex;
  justify-content: center;
  gap: 10px;
}

.table-action-btn:hover {
  transform: scale(1.05);
}

.empty-state {
  padding: 60px 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  color: #909399;
}

.empty-icon-wrapper {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background: rgba(79, 172, 254, 0.12);
  display: flex;
  align-items: center;
  justify-content: center;
}

.empty-icon {
  font-size: 48px;
  color: #4facfe;
}

.empty-text {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: #606266;
}

.empty-action-btn {
  margin-top: 8px;
  padding: 10px 24px;
  border-radius: 8px;
  background: linear-gradient(135deg, #00c6ff 0%, #0072ff 100%);
  border: none;
  color: #fff;
}

.table-pagination {
  margin-top: 24px;
  padding: 24px 28px;
  background: linear-gradient(
    135deg,
    rgba(79, 172, 254, 0.06) 0%,
    rgba(0, 242, 254, 0.04) 100%
  );
  border-radius: 14px;
  border: 1px solid rgba(79, 172, 254, 0.15);
  box-shadow: 0 2px 12px rgba(79, 172, 254, 0.08);
  transition: all 0.3s ease;
}

.table-pagination:hover {
  box-shadow: 0 4px 16px rgba(79, 172, 254, 0.12);
  border-color: rgba(79, 172, 254, 0.25);
}

.pagination-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 20px;
}

.pagination-info {
  display: flex;
  align-items: center;
  gap: 24px;
  flex-wrap: wrap;
}

.pagination-info-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 8px;
  border: 1px solid rgba(79, 172, 254, 0.2);
  transition: all 0.3s ease;
}

.pagination-info-item:hover {
  background: rgba(255, 255, 255, 1);
  border-color: rgba(79, 172, 254, 0.4);
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(79, 172, 254, 0.15);
}

.info-icon {
  font-size: 16px;
  color: #4facfe;
}

.pagination-text {
  font-size: 14px;
  color: #606266;
  font-weight: 400;
}

.highlight-number {
  color: #4facfe;
  font-weight: 700;
  font-size: 15px;
  margin: 0 2px;
}

.pagination-controls {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.pagination-buttons {
  display: flex;
  gap: 8px;
}

.pagination-btn {
  border-radius: 8px;
  padding: 10px 18px;
  font-weight: 500;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border: 1px solid rgba(79, 172, 254, 0.3);
  background: linear-gradient(135deg, #ffffff 0%, #f8fbff 100%);
  color: #4facfe;
  box-shadow: 0 2px 6px rgba(79, 172, 254, 0.1);
}

.pagination-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: #fff;
  border-color: transparent;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(79, 172, 254, 0.3);
}

.pagination-btn:active:not(:disabled) {
  transform: translateY(0);
  box-shadow: 0 2px 6px rgba(79, 172, 254, 0.2);
}

.pagination-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  background: #f5f7fa;
  color: #c0c4cc;
  border-color: #e4e7ed;
  box-shadow: none;
}

.pagination-btn-first,
.pagination-btn-last {
  font-weight: 600;
}

.btn-icon-right {
  margin-left: 4px;
  font-size: 14px;
}

.pagination-component {
  flex: 0 0 auto;
}

.pagination-component :deep(.el-pagination) {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination-component :deep(.el-pagination__sizes) {
  margin-right: 0;
}

.pagination-component :deep(.el-pagination .el-select) {
  width: 110px;
}

.pagination-component :deep(.el-pagination .el-select .el-input__inner) {
  border-radius: 8px;
  border: 1px solid rgba(79, 172, 254, 0.3);
  transition: all 0.3s ease;
}

.pagination-component :deep(.el-pagination .el-select .el-input__inner:hover) {
  border-color: rgba(79, 172, 254, 0.5);
}

.pagination-component :deep(.el-pager li) {
  border-radius: 8px;
  margin: 0 2px;
  min-width: 36px;
  height: 36px;
  line-height: 36px;
  transition: all 0.3s ease;
  border: 1px solid transparent;
}

.pagination-component :deep(.el-pager li:hover) {
  background: rgba(79, 172, 254, 0.1);
  border-color: rgba(79, 172, 254, 0.3);
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(79, 172, 254, 0.15);
}

.pagination-component :deep(.el-pager li.is-active) {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: #fff;
  border-color: transparent;
  font-weight: 600;
  box-shadow: 0 2px 8px rgba(79, 172, 254, 0.3);
}

.pagination-component :deep(.btn-prev),
.pagination-component :deep(.btn-next) {
  border-radius: 8px;
  margin: 0 4px;
  min-width: 36px;
  height: 36px;
  transition: all 0.3s ease;
  border: 1px solid rgba(79, 172, 254, 0.3);
  background: rgba(255, 255, 255, 0.9);
}

.pagination-component :deep(.btn-prev:hover),
.pagination-component :deep(.btn-next:hover) {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: #fff;
  border-color: transparent;
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(79, 172, 254, 0.2);
}

.pagination-component :deep(.btn-prev:disabled),
.pagination-component :deep(.btn-next:disabled) {
  opacity: 0.5;
  cursor: not-allowed;
  background: #f5f7fa;
  color: #c0c4cc;
  border-color: #e4e7ed;
}

@media (max-width: 768px) {
  .pagination-wrapper {
    flex-direction: column;
    align-items: stretch;
  }

  .pagination-info {
    justify-content: center;
    width: 100%;
  }

  .pagination-controls {
    justify-content: center;
    width: 100%;
  }

  .pagination-buttons {
    flex-wrap: wrap;
    justify-content: center;
  }
}
</style>
